#!/bin/bash

SHELL_DIR="$(realpath $(dirname $0))"
PROJECT_DIR="$(pwd)"

BINPATH="${SHELL_DIR}"

unpackimg() {
	"${BINPATH}/unpackimg.sh" $@
}

repackimg() {
	"${BINPATH}/repackimg.sh" $@
}

cleanup() {
	"${BINPATH}/cleanup.sh"
}

if [ -d "${PROJECT_DIR}" ]; then
	echo project dir exist.
fi

clear

main() {
	echo -e "1. Unpack boot image with magiskboot\n\n"
	echo -e "2. Repack boot image with magiskboot\n\n"
	echo -e "3. Clean up unpack dir\n\n"
	echo -e "4. Exit this function"
	read input
	case ${input} in
		1)
			cd "${PROJECT_DIR}"
			echo "Unpack boot image ..."
			if [ ! -f "boot.img" ]; then
				echo "boot.img does not exist ..."
				sleep 1
			else
				if [ -d "boot" ]; then rm -rf "boot" ; fi
				mkdir boot && cd boot
				unpackimg "../boot.img"
				sleep 1
			fi
			cd "${PROJECT_DIR}"
		;;
		2)
			cd "${PROJECT_DIR}"
			echo "Repack boot image ..."
			if [ ! -f "boot.img" ]; then
				echo "boot.img does not exist ..."
				sleep 1
			else
				if [ ! -d "boot" ]; then
					echo "unpacked boot folder not found ..."
					sleep 1
				else
					cd "boot"
					repackimg "../boot.img" ./
					sleep 1
				fi
			fi
			cd "${PROJECT_DIR}"
		;;
		3)
			cd "${PROJECT_DIR}"
			echo "Clean up unpack dir ..."
			cd "${PROJECT_DIR}"
			if [ -d "boot" ]; then
				cd "boot"
				cleanup
				sleep 1
			fi
			cd "${PROJECT_DIR}"
		;;
		4)
			echo "Exiting ..."
			sleep 1
			return 1
		;;
	esac
	return 0
}

while main
do
	clear
done